﻿using System.Net.Sockets;
using System;
using System.Net;

namespace Honeycomb.Transport.Ipv4Synchronous
{
    /// <summary>
    /// INetworkPeer implementation.
    /// </summary>
    public class NetworkPeer : INetworkPeer
    {
        /// <summary>
        /// TCP client.
        /// </summary>
        private readonly TcpClient tcpClient;

        /// <summary>
        /// Network stream.
        /// </summary>
        private readonly NetworkStream stream;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="tcpClient">TCP client instance.</param>
        public NetworkPeer(TcpClient tcpClient)
        {
            if (tcpClient == null) 
                throw new ArgumentNullException("tcpClient");

            this.tcpClient = tcpClient;
            stream = tcpClient.GetStream();
        }

        /// <summary>
        /// Get stream.
        /// </summary>
        /// <returns>Stream.</returns>
        public NetworkStream GetStream()
        {
            return stream;
        }

        /// <summary>
        /// Gets the network address of the Peer.
        /// </summary>
        public string Address
        {
            get { return ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString(); }
        }

        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            tcpClient.Close();
            stream.Dispose();
        }
    }
}
